package com.huayu.languo.common.framework;

import com.alibaba.fastjson.JSON;
import com.huayu.languo.model.dto.ResultDto;
import com.huayu.languo.model.enums.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

// 拦截登录失效的请求
@Slf4j
public class AdminAuthInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Value("${spring.profiles.active}")
    private String profilesActive;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        log.info("          Admin AuthInterceptor validate!!!");

        if (StringUtils.equalsIgnoreCase("dev", profilesActive)) {
            return true;
        }

        // 无论访问的地址是不是正确的，都进行登录验证，登录成功后的访问再进行分发，404的访问自然会进入到错误控制器中
        //HttpSession session = request.getSession(false);
        //if (null != session && session.getAttribute("loginUserId") != null) {
        //    try {
        //        // 验证当前请求的session是否是已登录的session
        //        String loginSessionId = redisTemplate.opsForValue().get("loginUser:" + session.getAttribute("loginUserId"));
        //        log.info("【login】session.getId [{}]  loginSessionId[{}]", session.getId(), loginSessionId);
        //        //TODO 可以通过这个控制 整个项目是否是 单点登录，还可以控制可以登录机器个数
        //        if (loginSessionId != null && loginSessionId.equals(session.getId())) {
        //            return true;
        //        }
        //    } catch (Exception e) {
        //        e.printStackTrace();
        //    }
        //}
        response401(response);
        return false;
    }

    private void response401(HttpServletResponse response) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        try {
            response.getWriter().print(JSON.toJSONString(ResultDto.failure(ResultCode.UNAUTHORIZED_401, null, "用户未登录")));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
